package com.itheima.test;

public class NewTicket implements Runnable {//同步代码块，同步方法，静态同步方法实现线程安全问题
    private static int ticketNumber = 100;//票数量起始为100张

    @Override
    public void run() {
        while (true) {
            if ("窗口一".equals(Thread.currentThread().getName())) {//同步方法
                boolean result = synchronizedMethod();
                if(result){
                    break;
                }
            }
            if ("窗口二".equals(Thread.currentThread().getName())) {//同步代码块
                synchronized (NewTicket.class){//静态同步方法对象为this,同步方法对象为类名.class
                    if(ticketNumber == 0){
                        break;
                    }else{
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        ticketNumber--;
                        System.out.println(Thread.currentThread().getName()+"正再买票,还剩下"+ticketNumber+"张");
                    }
                }
            }
        }
    }

    private static synchronized boolean synchronizedMethod() {//同步方法
        if (ticketNumber == 0) {
            return true;
        } else {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ticketNumber--;
            System.out.println(Thread.currentThread().getName()+"正再买票,还剩下"+ticketNumber+"张");
            return false;
        }
    }
}
